package com.jd.mskill.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jd.mskill.config.CommonConstants;
import com.jd.mskill.config.LaiTeKe;
import com.jd.mskill.config.R;
import com.jd.mskill.config.Zmdsms;
import com.jd.mskill.mapper.SysImgMapper;
import com.jd.mskill.mapper.SysPhoneMapper;
import com.jd.mskill.mapper.SysSmsAccountMapper;
import com.jd.mskill.mapper.SysTokenMapper;
import com.jd.mskill.po.SysImg;
import com.jd.mskill.po.SysPhone;
import com.jd.mskill.po.SysSmsAccount;
import com.jd.mskill.po.SysToken;
import com.jd.mskill.vo.X1y1x2y2x3y3x4y4;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class Task {

    @Resource
    private SysImgMapper sysImgMapper;

    @Autowired
    private LaiTeKe laiTeKe;

    @Autowired
    private Zmdsms zmdsms;

    @Resource
    private SysTokenMapper sysTokenMapper;

    @Resource
    private SysPhoneMapper sysPhoneMapper;

    @Resource
    private SysSmsAccountMapper sysSmsAccountMapper;


    @Scheduled(cron = "0/10 * * * * ?")
    public void phoneCanle() {
        log.info( "取消手机号码定时任务{}", new Date().toLocaleString() );
        long le = System.currentTimeMillis() - 60000;
        List<SysPhone> sysPhones = sysPhoneMapper.selectList( Wrappers.<SysPhone>lambdaQuery().eq( SysPhone::getIsCancel, CommonConstants.ZERO ).isNull(SysPhone::getCode).le( SysPhone::getCreateTime, new Date( le ) ) );
        if (CollUtil.isNotEmpty( sysPhones )) {
            SysToken sysToken = sysTokenMapper.selectOne( Wrappers.<SysToken>lambdaQuery().eq( SysToken::getDelFlag, 0 ) );
            for (SysPhone sysPhone : sysPhones) {
                try {
                    String cancel_url = String.format( "http://api.zmdsms.com/Cancel/?id=%s&phone=%s&token=%s", "16883", sysPhone.getPhone(), sysToken.getToken() );
                    HttpRequest.get( cancel_url ).timeout( 2000 ).execute();
                } catch (Exception e) {
                    log.error( "取消错误e:{} ,phone :{}", e, sysPhone.getPhone() );
                }
            }
        } else {
            log.info( "没有可以取消的号码" );
        }
    }


    //    @Scheduled(cron = "0 0 0/1 * * ? ")
    @Scheduled(cron = "0 0/1 * * * ? ")
//    @Scheduled(cron = "0/20 * * * * ?")
    public void phoneExecute() {
        String token_url = String.format("http://api.zmdsms.com/Login/?username=%s&password=%s", zmdsms.getZmdsms_username(), zmdsms.getZmdsms_password());
        HttpResponse execute = HttpRequest.get(token_url).timeout(2000).execute();
        String body = execute.body();
        String[] msg_split = body.split("\\|");
//        1|61b5a23f9b0b8a1b05bf62825828c47a|53.780|0.000
        if (Integer.valueOf(msg_split[0]) == 1) {
            SysToken sysToken = new SysToken(Integer.valueOf(msg_split[0]), msg_split[1], new BigDecimal(msg_split[2]), new BigDecimal(msg_split[3]), 0, new Date());
            sysTokenMapper.insert(sysToken);
            List<SysToken> sysTokens = sysTokenMapper.selectList(Wrappers.<SysToken>lambdaQuery().eq(SysToken::getDelFlag, CommonConstants.ZERO).notIn(SysToken::getId, sysToken.getId()));
            sysTokens.stream().forEach(it -> {
                it.setDelFlag(1);
                sysTokenMapper.updateById(it);
            });
        }
    }

    @Scheduled(cron = "0/10 * * * * ? ")
    public void synSmsAccount() {
        SysSmsAccount sysSmsAccount = sysSmsAccountMapper.selectOne(Wrappers.<SysSmsAccount>lambdaQuery().eq(SysSmsAccount::getDelFlag, CommonConstants.ZERO));
        if (ObjectUtil.isNull(sysSmsAccount)) {
            return;
        }
        zmdsms.setZmdsms_username(sysSmsAccount.getSmsUsername());
        zmdsms.setZmdsms_password(sysSmsAccount.getSmsPassword());
    }


//    @Scheduled(cron = "0/5 * * * * ?")
    public void execute() {
        long nowC = System.currentTimeMillis();
        Date gt = new Date(nowC - 15000);
        Date lt = new Date(nowC - 5000);
        List<SysImg> sysImgs = sysImgMapper.selectList(Wrappers.<SysImg>lambdaQuery().isNull(SysImg::getX1y1).between(SysImg::getCreate_time, lt, gt));
        if (CollUtil.isEmpty(sysImgs)) {
            log.info("执行时间为结束时间：{}", new Date().toLocaleString());
            return;
        } else {
            List<String> picMd5s = sysImgs.stream().map(SysImg::getPicMd5).collect(Collectors.toList());
            log.info("没有识别到的数据：{}", picMd5s);
        }
        for (SysImg sysImg : sysImgs) {
            String get_url = String.format("http://laiket.cn:7777/get?user=%s&pwd=%s&type=%s&do=get&picMD5=%s", laiTeKe.getLai_te_ke_username(),
                    laiTeKe.getLai_te_ke_password(), "20002", sysImg.getPicMd5());
            try {
                HttpResponse execute = HttpRequest.get(get_url).header("Encoding", "UTF8").timeout(2000).execute();
                log.info("第一次请求结果是:{}", URLDecoder.decode(execute.body(), "utf-8"));
                if (execute.body().contains("1001")) {
                    R r = buildPicImg(execute.body(), sysImg.getPicMd5(), sysImg.getImgData());
                    if (r.getCode() == CommonConstants.SUCCESS) {
                        continue;
                    }
                }
            } catch (Exception e) {
                log.info("请求失败,原始数据：{}", sysImg);
            }
        }
        log.info("执行时间为结束时间：{}", new Date().toLocaleString());
    }

    private R buildPicImg(String body, String picMd5, String data) throws Exception {
        String msg = URLDecoder.decode(body, "utf-8");
        msg = msg.substring("code:1001,msg:".length());
        String[] msg_split = msg.split("\\|");
        if (msg_split.length == 4) {
            log.info("查询数据为md5的值为:{},数据为", picMd5, msg_split);
            int x2 = Integer.valueOf(msg_split[1].split(",")[0]);
            int x1 = Integer.valueOf(msg_split[0].split(",")[0]);
            int x4 = Integer.valueOf(msg_split[3].split(",")[0]);
            int x3 = Integer.valueOf(msg_split[2].split(",")[0]);
            int y1 = Integer.valueOf(msg_split[0].split(",")[1]);
            int y3 = Integer.valueOf(msg_split[2].split(",")[1]);
            int y2 = Integer.valueOf(msg_split[1].split(",")[1]);
            int y4 = Integer.valueOf(msg_split[3].split(",")[1]);
            SysImg sysImgDb = sysImgMapper.selectOne(Wrappers.<SysImg>lambdaQuery().eq(SysImg::getPicMd5, picMd5));
            X1y1x2y2x3y3x4y4 x1y1x2y2x3y3x4y4 = new X1y1x2y2x3y3x4y4(x1, x2, x3, x4, y1, y2, y3, y4);
            if (ObjectUtil.isNotNull(sysImgDb)) {
                SysImg sysImgNew = new SysImg(sysImgDb.getId(), picMd5, data, JSON.toJSONString(x1y1x2y2x3y3x4y4), 0, new Date());
                log.debug("");
                sysImgMapper.updateById(sysImgNew);
            }
            return R.ok(JSON.toJSONString(x1y1x2y2x3y3x4y4));
        }
        return R.ok();
    }


}
